package com.atguigu.lease.web.admin.service.impl;

import com.atguigu.lease.common.minio.minioproperties;
import com.atguigu.lease.web.admin.service.FileService;
import io.minio.*;
import io.minio.errors.*;
import lombok.RequiredArgsConstructor;
import org.apache.commons.compress.harmony.pack200.PackingUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Set;
import java.util.UUID;
@RequiredArgsConstructor
@Service
public class FileServiceImpl implements FileService {
    private  final MinioClient minioClient;
    @Autowired
    private minioproperties minioproperties;
    @Override
    public String upload(MultipartFile file) throws ServerException, InsufficientDataException, ErrorResponseException, IOException, NoSuchAlgorithmException, InvalidKeyException, InvalidResponseException, XmlParserException, InternalException {

            boolean b = minioClient.bucketExists(BucketExistsArgs.builder().bucket(minioproperties.getBucketName()).build());
            if(!b)
            {
                minioClient.makeBucket(MakeBucketArgs.builder().bucket(minioproperties.getBucketName()).build());
                minioClient.setBucketPolicy(SetBucketPolicyArgs.builder().bucket(minioproperties.getBucketName())
                        .config(createBucketPolicyConfig(minioproperties.getBucketName()))
                        .build());

            }
            String filename = new SimpleDateFormat("yyyyMMdd").format(new Date()) + "/" + UUID.randomUUID() + "-" + file.getOriginalFilename();
            minioClient.putObject(PutObjectArgs.builder()
                    .bucket(minioproperties.getBucketName())
                    .stream(file.getInputStream(), file.getSize(),-1)//因为这不是file类型
                    .object(filename)
                    .contentType(file.getContentType())//原始要下载
                    .build());
            String url=minioproperties.getEndpoint()+"/"+minioproperties.getBucketName()+"/"+filename;
            return url;
    }
    private String createBucketPolicyConfig(String bucketName) {
        return """
                  {
                    "Statement" : [ {
                      "Action" : "s3:GetObject",
                      "Effect" : "Allow",
                      "Principal" : "*",
                      "Resource" : "arn:aws:s3:::%s/*"
                    } ],
                    "Version" : "2012-10-17"
                  }
                  """.formatted(bucketName);
    }
}
